import {deleteSysCode, querySysCode, saveSysCode} from '@/services/systemManage/dict'
import {message} from 'ant-design-vue'
import {findIndex} from 'lodash'
import {storePrompt} from '@/store/modules/commonStore'

export default {
  namespaced: true,
  state: {
    treeInfo: [],
    disable: true,
    parentId: '',
    tableData: [],
    pagination: {},
    queryData: {}
  },
  getters: {
    getTreeInfo(state) {
      let data = []
      state.treeInfo.map((value) => {
        data.push({
          title: value.name,
          key: value.objectId,
          scopedSlots: {title: 'title'}
        })
      })
      return data
    },

    getTreeInfoById: (state) => (payload) => {
      let index = findIndex(state.treeInfo, function (o) {
        return o.objectId == payload;
      });
      return state.treeInfo[index]
    },

    getTableDataById: (state) => (payload) => {
      let {records} = state.tableData
      let index = findIndex(records, function (o) {
        return o.objectId == payload;
      });
      return records[index]
    },

    getTableData(state) {
      let {records} = state.tableData
      if (records) {
        records = records.map((value) => {
          return {
            ...value, key: value.objectId
          }
        })
      }
      return records
    }

  },
  actions: {

    async saveActions({commit}, payload) {
      let info = false
      await saveSysCode(payload.values, payload.url).then((obj) => {
        let {success} = obj.data;
        info = success
        storePrompt(success)
      })
      return info
    },

    async queryTreeInfo({commit, state}, payload) {
      let {pageSize} = payload
      querySysCode(payload).then((obj) => {
        let {data, success} = obj.data;
        if (success) {
          if (pageSize < 0) {
            commit('setState', {name: 'treeInfo', value: data})
          } else {
            commit('setState', {name: 'tableData', value: data})
            let {total, current} = data
            commit('setState', {
              name: 'pagination',
              value: {...state.pagination, total: Number(total), current: Number(current)}
            })
          }
        }
      })
    },

    async deleteCode({dispatch, state}, payload) {
      let {objectId, child} = payload
      deleteSysCode(objectId).then((obj) => {
        let {success} = obj.data;
        if (success) {
          if (child) {
            dispatch('queryTreeInfo', {parentId: state.parentId[0]})
          } else {
            dispatch('queryTreeInfo', {pageSize: -1})
          }
          message.success('操作成功！', 3)
        } else {
          message.error('操作失败！', 3)
        }
      })
    }


  },

}